package com.yunbiao.ybbusstopplate.utils.core.play;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.Typeface;
import android.text.TextUtils;
import android.view.Display;
import android.view.Gravity;
import android.view.WindowManager;
import android.widget.AbsoluteLayout;
import android.widget.AbsoluteLayout.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TextView;


import com.yunbiao.ybbusstopplate.utils.cache.LayoutCache;
import com.yunbiao.ybbusstopplate.utils.core.TYTool;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.concurrent.ExecutorService;

@SuppressWarnings("deprecation")
public class CreateElement {
    private static final String TAG = "CreateElement";
    public static Integer TOOL_HEIGHT = 70;
    public static Integer FOOT_HEIGHT = 70;

    /**
     * 创建TextView
     */
    @SuppressLint("RtlHardcoded")
    public static TextView addTextView(Context context, LayoutInfo layoutInfo, WindowManager wm) {
        LayoutPosition lp = LayoutJsonTool.getViewPostion(layoutInfo, wm);

        LayoutParams layoutParams = new LayoutParams(lp.getWidth(), lp.getHeight(), lp.getLeft(), lp.getTop());

        TextDetail textDetail = layoutInfo.getTextDetail();
        final TextView marquee = new TextView(context);
        marquee.setTextSize(textDetail.getFontSize());

        StringBuilder sb = new StringBuilder("");
        String[] content = layoutInfo.getContent();
        for (String aContent : content) {
            sb.append(aContent).append("  ");
        }
        marquee.setText(sb.toString());

        String textAlign = textDetail.getTextAlign();
        if (TextUtils.isEmpty(textAlign) || textAlign.equals("center")) {
            marquee.setGravity(Gravity.CENTER);
        } else if (textAlign.equals("left")) {
            marquee.setGravity(Gravity.LEFT);
        } else if (textAlign.equals("right")) {
            marquee.setGravity(Gravity.RIGHT);
        }

        marquee.setLayoutParams(layoutParams);
        try {
            marquee.setTextColor(Color.parseColor(textDetail.getFontColor()));
        } catch (NumberFormatException e) {
            marquee.setTextColor(Color.parseColor("#000000"));
        }
        try {
            marquee.setBackgroundColor(Color.parseColor(textDetail.getBackground()));
        } catch (NumberFormatException e) {
            marquee.setBackgroundColor(Color.parseColor("#ffffff"));
        }
        setTextFont(context, marquee, textDetail.getFontFamily());

        return marquee;
    }

    /**
     * 创建滚动文本
     */
    public static LinearLayout addScrollTextView(Context context, LayoutInfo layoutInfo, WindowManager wm) {
        LayoutPosition lp = LayoutJsonTool.getViewPostion(layoutInfo, wm);
        LayoutParams layoutParams = new LayoutParams(lp.getWidth(), lp.getHeight(), lp.getLeft(), lp.getTop());

        LinearLayout linearLayout = new LinearLayout(context);
        linearLayout.setLayoutParams(layoutParams);
        linearLayout.setPadding(0, 0, 0, 0);

        TextDetail textDetail = layoutInfo.getTextDetail();

        final MyScrollTextView scrollTv = new MyScrollTextView(context);
        scrollTv.setTextSize(textDetail.getFontSize());
        try {
            scrollTv.setTextColor(Color.parseColor(textDetail.getFontColor()));
        } catch (Exception e) {
//            e.printStackTrace();
            scrollTv.setTextColor(Color.parseColor("#000000"));
        }

        scrollTv.setLayoutParams(layoutParams);
        scrollTv.setTextFont(context, textDetail.getFontFamily());

        //判断处理文本内容
        StringBuilder scrollSb = new StringBuilder("");
        String[] content = layoutInfo.getContent();
        for (String aContent : content) {
            scrollSb.append(aContent).append("  ");
        }
        scrollTv.setText(scrollSb.toString());

        scrollTv.setScrollSpeed(textDetail.getPlayTime());

        if (Integer.parseInt(textDetail.getPlayType()) == 0) {
            scrollTv.setDirection(3);//向上滚动0,向左滚动3,向右滚动2,向上滚动1
        } else if (Integer.parseInt(textDetail.getPlayType()) == 1) {
            scrollTv.setDirection(0);
        }

        try {
            scrollTv.setBackColor(Color.parseColor(textDetail.getBackground()));
        } catch (Exception e) {
//            e.printStackTrace();
            scrollTv.setBackColor(Color.parseColor("#ffffff"));
        }

        linearLayout.addView(scrollTv);
        return linearLayout;
    }

    private static Bitmap readBitmapAutoSize(String filePath, int outWidth, int outHeight) {
        // outWidth和outHeight是目标图片的最大宽度和高度，用作限制
        Bitmap bitmap = null;
        try {
            File file = new File(filePath);
            if (file.exists()) {
                BitmapFactory.Options options = setBitmapOption(filePath, outWidth, outHeight);
                bitmap = BitmapFactory.decodeFile(file.getPath(), options);
            }
        } catch (OutOfMemoryError | Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    private static BitmapFactory.Options setBitmapOption(String file, int width, int height) {
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inJustDecodeBounds = true;
        // 设置只是解码图片的边距，此操作目的是度量图片的实际宽度和高度
        BitmapFactory.decodeFile(file, opt);
        int outWidth = opt.outWidth; // 获得图片的实际高和宽
        int outHeight = opt.outHeight;
        opt.inDither = false;
        opt.inPreferredConfig = Bitmap.Config.ARGB_4444;
        // 设置加载图片的颜色数为16bitRGB_565，默认是RGB_8888，表示24bit颜色和透明通道，但一般用不上
        opt.inSampleSize = 1;
        // 设置缩放比,1表示原比例，2表示原来的四分之一....
        // 计算缩放比
        if (outWidth != 0 && outHeight != 0 && width != 0 && height != 0) {
            int sampleSize = (outWidth / width + outHeight / height) / 2;
            opt.inSampleSize = sampleSize;
        }
        opt.inJustDecodeBounds = false;// 最后把标志复原
        return opt;
    }






    /**
     * 头部布局
     *
     * @param context
     * @param wm
     * @param layout
     * @param layoutMenu
     */
    private static ExecutorService executor;


    /**
     * 设置文本字体
     */
    private static void setTextFont(Context context, TextView textView, String fontFamily) {
        if (!isNumeric(fontFamily)) {
            return;
        }
        int index = Integer.parseInt(fontFamily);
        if (index == 4 || index == 5) {
            index = 1;
        }
        if (index != 1) {
            Typeface typeFace = Typeface.createFromAsset(context.getAssets(), "fonts/" + fonts[index - 2]);
            textView.setTypeface(typeFace);
        }
    }

    /**
     * 创建foot
     *
     * @param context
     * @param wm
     * @param layout
     * @param layoutFoot
     */
    public static void createLayoutFoot(Context context, WindowManager wm, AbsoluteLayout layout, LayoutFoot layoutFoot) {
        if (layoutFoot != null && layoutFoot.getEnabled()) {
            FOOT_HEIGHT = 70;

            Display display = wm.getDefaultDisplay();
            Point point = new Point();
            display.getRealSize(point);
            int width = point.x;
            int height = point.y;

            String isMirror = LayoutCache.getIsMirror();
            LayoutParams layoutParams = new LayoutParams(width, 70, 0, height - 70);
            if (layoutFoot.getIsPlay().equals("true")) {
                MyScrollTextView marquee = new MyScrollTextView(context);
                marquee.setTag("footView");
                if (layoutFoot.getFooterText().isEmpty()) {
                    BufferedReader bufferedReader = null;
                    try {
                        // 文字内容
                        File[] files = new File(TYTool.getSdcardPath() + "/yunbiao/news").listFiles();
                        bufferedReader = new BufferedReader(new FileReader(files[0]));
                        String text = bufferedReader.readLine();
                        if (text.length() > 100) {
                            text = text.substring(0, 99);
                        }
                        layoutFoot.setFooterText(text);
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        if (bufferedReader != null)
                            try {
                                bufferedReader.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                    }
                }
                if (isMirror.equals("1")) {
                    marquee.setTextColor(Color.parseColor("#ffffff"));
                    marquee.setBackColor(Color.parseColor("#000000"));
                } else {
                    marquee.setTextColor(Color.parseColor(layoutFoot.getFontColor()));
                    marquee.setBackColor(Color.parseColor(layoutFoot.getBackground()));
                }

                marquee.setText(layoutFoot.getFooterText());
                marquee.setTextSize(layoutFoot.getFontSize());
                marquee.setTextFont(context, layoutFoot.getFontFamily());
                marquee.setLayoutParams(layoutParams);

                // 慢0.2 较慢 0.5 正常 1 较快 2 快 3
                marquee.setDirection(3);
                marquee.setScrollSpeed(layoutFoot.getPlayTime());
                layout.addView(marquee);
            } else {
                TextView marquee = new TextView(context);
                marquee.setText(layoutFoot.getFooterText());
                marquee.setTextSize(layoutFoot.getFontSize());
                marquee.setTag("footView");
                if (isMirror.equals("1")) {
                    marquee.setTextColor(Color.parseColor("#ffffff"));
                    marquee.setBackgroundColor(Color.parseColor("#000000"));
                } else {
                    marquee.setTextColor(Color.parseColor(layoutFoot.getFontColor()));
                    marquee.setBackgroundColor(Color.parseColor(layoutFoot.getBackground()));
                }

                setTextFont(context, marquee, layoutFoot.getFontFamily());
                marquee.setLayoutParams(layoutParams);
                marquee.setSingleLine(true);
                marquee.setGravity(Gravity.CENTER);
                layout.addView(marquee);
            }
        } else {
            FOOT_HEIGHT = 0;
        }
    }

    private static String[] fonts = new String[]{"song.ttf", "kai.ttf"};

    private static boolean isNumeric(String str) {
        if (TextUtils.isEmpty(str)) {
            return false;
        }
        for (int i = 0; i < str.length(); i++) {
            if (!Character.isDigit(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }

}
